<template>
  <div class="popup">
    <header>
      <div class="form">
        <i class="iconfont icon-sousuo" @click="onSearch"></i>
        <i class="iconfont icon-shanchu" @click="clearVal"></i>
        <input
          type="text"
          v-model.lazy="searchVal"
          placeholder="请输入搜索关键词"
          @keyup.enter="onSearch"
        />
      </div>
      <div class="cancel" @click="onCancel">取消</div>
    </header>
    <hotHistory
      :hot="hot"
      v-if="blockShow === 1"
      :readHistory="history"
      @goSearch="goSearch"
      @saveHistory="saveHistory"
      @confirmDele="confirmDele"
    ></hotHistory>
    <SearchSuggest v-else-if="blockShow == 2" :word="word"></SearchSuggest>
    <div v-else>
      <Loading v-if="isLoading" />
      <searchResults
        v-else
        :books="books"
        ref="resultChild"
        @bookchange="bookchange"
      ></searchResults>
    </div>
  </div>
</template>

<script>
import { hotWord, searchSuggest, searchResult } from "@/request/api";
import hotHistory from "@/components/hotHistory";
import SearchSuggest from "../components/searchSuggest.vue";
import searchResults from "../components/searchResult.vue";
export default {
  components: {
    hotHistory,
    SearchSuggest,
    searchResults,
  },

  data() {
    return {
      isLoading: true,
      blockShow: 1,
      searchVal: "",
      history: [],
      hot: [],
      word: [],
      books: {
        list: [],
        name: "书城",
      },
      params: {
        sort: 0,
        channel: 0,
        bookStatus: 0,
        pay: 0,
        wordCount: 0,
        page: 1,
      },
      imgUrl: require("../assets/images/default.png"),
    };
  },
  watch: {
    searchVal(newVal, oldVal) {
      if (newVal == "") {
        this.blockShow = 1;
        return;
      }
    },
  },
  methods: {
    //清空历史记录
    confirmDele() {
      this.$dialog
        .confirm({
          width: "400px",
          confirmButtonText: "删除",
          message: "是否清空最近搜索？",
        })
        .then(() => {
          localStorage.removeItem("yunread-searchHistory");
          this.history = [];
        })
        .catch(() => {});
    },
    //清空输入框
    clearVal() {
      this.searchVal = "";
    },
    //点击最近搜索,
    goSearch(val) {
      this.searchVal = val;
      let obj = {
        keyCode: 13,
      };
      this.onSearch(obj);
    },
    //保存历史记录
    saveHistory(obj) {
      this.history =
        JSON.parse(localStorage.getItem("yunread-searchHistory")) || [];
      let index = this.history.findIndex((v) => v.name == obj.val);
      if (index == -1) {
        this.history.push({
          bookid: obj.ishot ? obj.bookid : "",
          ishot: obj.ishot || false,
          name: obj.val,
        });
        localStorage.setItem(
          "yunread-searchHistory",
          JSON.stringify(this.history)
        );
      }
    },
    //点击返回按钮
    onCancel() {
      if (this.blockShow == 1) {
        this.$router.go(-1);
        // this.$router.push(
        //   "/bookcity/recommend?type=female_recommend&uuid=b229b022871941fea35edc7aceeed1ab"
        // );
      }
      if (this.blockShow == 3) {
        this.blockShow = 1;
      }
    },

    //
    searching(i) {
      console.log(i);
      if (i == 1) {
        this.books.list = [];
        this.getData();
      } else if (i == 2) {
        this.getData();
      }
    },
    //向服务器发送请求
    getData() {
      searchResult({
        keyword: this.searchVal,
        page: this.params.page,
        sort: this.params.sort,
        channel: this.params.channel,
        bookStatus: this.params.bookStatus,
        pay: this.params.pay,
        wordCount: this.params.wordCount,
      }).then((res) => {
        if (res.code == 0) {
          this.isLoading = false;
          let books = JSON.parse(
            JSON.stringify(res.data.books).replace(/summary/g, "content")
          );
          books.map((v) => {
            let index = v.cover.indexOf("?");
            if (index > -1) {
              v.cover = this.imgUrl;
            }
          });
          this.books.list = [...this.books.list, ...books];
        }
      });
    },
    onSearch() {
      if (this.searchVal.trim() == "") {
        return;
      }
      //存储搜索历史
      this.saveHistory({ val: this.searchVal, ishot: false });
      //

      this.blockShow = 3;
      this.books.list = [];
      this.isLoading = false;
      this.searching(1);
    },
    bookchange(params) {
      this.params = params;
      this.searching(params.type);
    },
    // onInput() {
    //   if (this.searchVal == "") {
    //     this.blockShow = 1;
    //   } else {
    //     searchSuggest({
    //       search: this.searchVal,
    //     }).then((res) => {
    //       this.blockShow = 2;
    //       this.word = res.words.w;
    //     });
    //   }
    // },
    init() {
      hotWord().then((res) => {
        this.hot = res.list;
        this.history =
          JSON.parse(localStorage.getItem("yunread-searchHistory")) || [];
      });
    },
  },
  activated() {
    if (!this.$route.meta.isBack) {
      this.init();
    }
    this.$route.meta.isBack = false;
  },
  beforeRouteEnter(to, from, next) {
    if (from.name == "xiangqing") {
      to.meta.isBack = true;
    }
    next();
  },
  created() {
    if (!this.$route.meta.isBack) {
      this.init();
    }
    this.$route.meta.isBack = false;
  },
};
</script>

<style lang="scss" scoped>
.popup {
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  padding: 0 14px;
  box-sizing: border-box;
  background-color: #fff;
}
header {
  display: flex;
  align-items: center;
  width: 100%;
  height: 60px;
  box-sizing: border-box;
  font-size: 16px;
  .form {
    flex: 1;
    height: 40px;
    position: relative;
    font-size: 16px;
  }
  input {
    width: 90%;
    height: 95%;
    padding-left: 50px;
    border-radius: 15px;
    vertical-align: middle;
    background-color: #eee;
  }
  @mixin position() {
    position: absolute;
    top: 50%;
    transform: translate(50%, -50%);
  }
  .icon-sousuo {
    @include position;
    left: 0;
    font-size: 26px;
  }
  .icon-shanchu {
    right: 0px;
    @include position;
    font-size: 24px;
    background-color: #fff;
    border-radius: 24px;
  }
  .cancel {
    width: 60px;
    text-align: right;
    background-color: #fff;
  }
}
</style>
